package io.nio;

import java.nio.ByteBuffer;

public class ByteBufferDemo {
    public static void main(String[] args) {
//        ByteBuffer buffer = ByteBuffer.allocate(4);
        ByteBuffer buffer = ByteBuffer.allocateDirect(4);
        System.out.printf("新创建， position -> %d, limit -> %d, capacity -> %d\n", buffer.position(), buffer.limit(), buffer.capacity());
        buffer.put((byte) 1);
        buffer.put((byte) 2);
        buffer.put((byte) 3);
        System.out.printf("put3个数据后， position -> %d, limit -> %d, capacity -> %d\n", buffer.position(), buffer.limit(), buffer.capacity());

        buffer.flip();
        System.out.printf("flip后， position -> %d, limit -> %d, capacity -> %d\n", buffer.position(), buffer.limit(), buffer.capacity());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.printf("get2个数据后， position -> %d, limit -> %d, capacity -> %d\n", buffer.position(), buffer.limit(), buffer.capacity());

        buffer.compact(); // 清理已读取数据
        System.out.printf("compact后， position -> %d, limit -> %d, capacity -> %d\n", buffer.position(), buffer.limit(), buffer.capacity());
        buffer.put((byte) 4);
        buffer.put((byte) 5);
        System.out.printf("再次put2个数据后， position -> %d, limit -> %d, capacity -> %d\n", buffer.position(), buffer.limit(), buffer.capacity());
    }
}
